package com.guan.core;

import com.guan.core.entity.PageData;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 控制器的基类
 * Created by Administrator on 2018/1/16 0016.
 */
@SuppressWarnings("all")
public class BaseController {
    protected Logger logger = Logger.getLogger(BaseController.class);
    /**
     * ThreadLocal 线程安全的特殊类
     * 会存在每一个子线程中 开着一个内存空间
     * 生命周期只有当前线程
     */
    private static ThreadLocal<HttpServletRequest> request = new ThreadLocal<HttpServletRequest>();
    private static ThreadLocal<HttpServletResponse> response = new ThreadLocal<HttpServletResponse>();
    private static ThreadLocal<PageData> pageData = new ThreadLocal<PageData>();
    public void init(HttpServletRequest request,HttpServletResponse response){
        this.request.set(request);
        this.response.set(response);
        pageData.set(new PageData(request));
    }
    public PageData getPageDate(){
        return this.pageData.get();
    }
    public Object getSeesionAttr(String atr){
        return  this.request.get().getSession().getAttribute(atr);
    }
    public void setSessionAttr(String attr,Object o){
        this.request.get().getSession().setAttribute(attr,o);
    }
    /**
     * 拿到当前的请求对象
     * @return
     */
    protected HttpServletRequest getReq(){
        return this.request.get();
    }

    /**
     * 拿到当前的响应对象
     * @return
     */
    protected HttpServletResponse getRep(){
        return this.response.get();
    }

    /**
     * 给请求域中添加数据
     * @param attrName
     * @param attrValue
     */
    protected void put(String attrName,Object attrValue){
        request.get().setAttribute(attrName,attrValue);
    }

    /**
     * 从求情域中拿参数
     * @param attrName
     * @return
     */
    protected Object get(String attrName){
        return request.get().getAttribute(attrName);
    }

    /**
     * 像前台输出一个字符串
     */
    protected void writerToResponse(String str){
        PrintWriter writer = null;
        try {
            writer = getRep().getWriter();
            writer.print(str);
            writer.close();
        } catch (IOException e) {
            logger.error("baseController中response写到前台错误",e.getCause());
        }
    }
}
